package x.ovo.wechat.bot.plugin.push;

import java.io.IOException;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;

/**
 * Author: wxy97.com
 * Date: 2024/9/30 11:29
 * Description:
 */
@Slf4j(topic = "DingDingPushStrategy")
public class DingDingPushStrategy implements PushStrategy {

    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=";

    @Override
    public void push(Map<String, ?> config, OkHttpClient client, String flag, String content) {
        String accessToken = (String) config.get("access_token_dingding");
        if (StrUtil.isBlank(accessToken)) accessToken = (String) config.get("access_token");
        if (StrUtil.isBlank(accessToken)) log.info("钉钉推送：配置文件未配置“access_token_dingding”");
        else {
            String secret = String.valueOf(config.get("secret"));
            JSONObject json = JSONUtil.ofObj()
                    .set("msgtype", "text")
                    .set("text", JSONUtil.ofObj().set("content", flag + ": " + content));
            Request request = new Request.Builder()
                    .url(URL + accessToken)
                    .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
                    .build();
            try (Response response = client.newCall(request).execute()) {
                JSONObject object = JSONUtil.parseObj(response.body().string());
                if (object.getInt("errcode") == 0 && object.getStr("errmsg").equals("ok")) {
                    log.info("钉钉推送成功");
                } else {
                    log.error("钉钉推送失败");
                }
            } catch (IOException e) {
                log.error("钉钉推送失败: {}", e.getMessage());
            }
        }
    }
}